package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"website/cache"
	"website/models"
)

type NewsController struct {
	beego.Controller
}

func (c *NewsController) NewsAdd() {
	uid, _ := c.GetInt("uid")
	title := c.GetString("title")
	content := c.GetString("content")
	if uid == 0 || title == "" || content == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "有参数为空",
		}
		c.ServeJSON()
		return
	}

	file, header, err := c.GetFile("picture")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "Upload failed",
		}
		c.ServeJSON()
		return
	}
	defer file.Close()

	fmt.Println(header.Size)
	if header.Size > 1024*1024*2 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "封面不能超过2M",
		}
		c.ServeJSON()
		return
	}

	path := "static/img/" + header.Filename
	err = c.SaveToFile("picture", path)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "Save file failed",
		}
		c.ServeJSON()
		return
	}

	PictureUrl := "http://127.0.0.1:8080/" + path

	news := models.News{
		Title:   title,
		Content: content,
		Uid:     uid,
		Picture: PictureUrl,
	}
	if err := models.DB.Table("news").Create(&news).Error; err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "添加小说失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}

func (c *NewsController) NewsList() {

	uid, _ := c.GetInt("uid")
	title := c.GetString("title")
	query := models.DB.Table("news")
	if title != "" {
		query = query.Where("title like ?", "%"+title+"%")
	}
	if uid != 0 {
		query = query.Where("uid = ?", uid)
	}

	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	offset := (page - 1) * size

	var count int64
	query.Count(&count)
	sum := int(math.Ceil(float64(count) / float64(size)))
	fmt.Println(sum)

	var news []models.News

	//列表缓存
	key := fmt.Sprintf("news_list_%s_%d_%d", title, uid, page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData != "" {
		json.Unmarshal([]byte(cacheData), &news)
	} else {
		err := query.Limit(size).Offset(offset).Find(&news).Error
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "查询失败",
			}
			c.ServeJSON()
			return
		}
		// 序列化
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, key, jsonData, 0)
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
		"data": news,
	}

	c.ServeJSON()
	return
}

func (c *NewsController) NewsDel() {
	id, _ := c.GetInt("id")

	var news models.News
	err := models.DB.Table("news").Where("id = ?", id).First(&news).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "新闻有误",
		}
		c.ServeJSON()
		return
	}

	if news.Num > 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "有阅读量，禁止删除",
		}
		c.ServeJSON()
		return
	}

	brr := models.DB.Table("news").Where("id = ?", id).Delete(&news).Error
	if brr != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}
